<template>
    <div class="product-detail-container">
        <h2>商品详情</h2>
        <div v-if="loading" class="loading-state">
            <el-skeleton :rows="6" animated />
        </div>
        <div v-else-if="error" class="error-state">
            <el-alert :title="`⚠️ 加载失败：${error}`" type="error" show-icon>
                <template #default>
                    <el-button type="primary" @click="fetchProductDetails" class="retry-btn">重试</el-button>
                </template>
            </el-alert>
        </div>
        <template v-else>
            <el-card class="product-card" shadow="hover">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <div class="product-image-wrapper">
                            <el-image :src="product.adimg || '/default-ad.png'" :alt="product.title" class="product-image"
                                fit="cover" @error="handleImageError" />
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="product-info">
                            <h3>{{ product.title }}</h3>
                            <p>{{ product.description }}</p>
                            <p><strong>价格：</strong>¥{{ product.price.toFixed(2) }}</p>
                            <p><strong>库存：</strong>{{ product.stock }}</p>
                            <p><strong>类别：</strong>{{ product.categoryname }}</p>
                            <p><strong>上架状态：</strong>
                                <el-tag :type="statusClass">{{ product.onsale ? '启用' : '停用' }}</el-tag>
                            </p>
                        </div>
                    </el-col>
                </el-row>
            </el-card>
            <el-upload class="upload-demo" action="" :on-change="handleAdImageUpload" :auto-upload="false"
                :show-file-list="false" accept="image/*">
                <el-button type="primary">点击上传广告图片</el-button>
                <template #tip>
                    <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </template>
            </el-upload>
            <el-button class="update-ad-btn" type="success" @click="updateAdImage">更新广告图片</el-button>
            <el-button class="edit-btn" type="primary" @click="editProduct">编辑</el-button>
            <el-button class="back-btn" type="info" @click="goBack">返回</el-button>
        </template>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getProductById, addAdimg } from '../../api/product';

const route = useRoute();
const router = useRouter();

// 响应式数据
const product = ref(null);
const loading = ref(true);
const error = ref(null);
const adImageFile = ref(null);

// 计算状态类
const statusClass = computed(() => {
    return product.value?.onsale ? 'success' : 'danger';
});

// 图片加载失败处理
const handleImageError = (e) => {
    console.error('广告图片加载失败:', e.target.src);
};

// 获取商品数据
const fetchProductDetails = async () => {
    try {
        loading.value = true;
        error.value = null;
        const productId = route.params.productid;
        console.log('根据商品id查询商品详情参数:', productId);

        if (!productId) {
            throw new Error('无效的商品ID');
        }

        const response = await getProductById(productId);
        console.log('根据商品id查询商品详情数据:', response.data);

        if (response.data?.code === 1) {
            product.value = response.data.data || null;

            if (!product.value) {
                throw new Error('商品不存在');
            }
        } else {
            throw new Error(response.data?.msg || '获取商品失败');
        }
    } catch (err) {
        console.error('商品详情加载失败:', err);
        error.value = err.message || '网络请求失败，请稍后重试';
    } finally {
        loading.value = false;
    }
};

// 返回上一页
const goBack = () => {
    router.back();
};

// 编辑商品
const editProduct = () => {
    router.push({ name: 'editProduct', params: { productid: product.value.productid } });
};

// 处理广告图片上传
const handleAdImageUpload = (file) => {
    adImageFile.value = file.raw;
};

// 更新广告图片
const updateAdImage = async () => {
    if (!adImageFile.value) {
        error.value = '请选择广告图片';
        return;
    }

    try {
        loading.value = true;
        error.value = null;

        const response = await addAdimg(product.value.productid, adImageFile.value);
        console.log('更新广告图片数据:', response.data);

        if (response.data?.code === 1) {
            // 更新 product.adimg 以显示新的广告图片
            product.value.adimg = response.data.data.adimgUrl || response.data.data.adimg;
            error.value = null;
        } else {
            throw new Error(response.data?.msg || '更新广告图片失败');
        }
    } catch (err) {
        console.error('更新广告图片失败:', err);
        error.value = err.message || '网络请求失败，请稍后重试';
    } finally {
        loading.value = false;
    }
};

onMounted(() => {
    fetchProductDetails();
});
</script>

<style scoped>
/* 基础样式 */
.product-detail-container {
    padding: 1rem;
    min-height: 100vh;
    background: #f5f5f5;
}

/* 编辑按钮 */
.edit-btn {
    margin-bottom: 1rem;
}

/* 返回按钮 */
.back-btn {
    margin-bottom: 1rem;
}

/* 更新广告图片按钮 */
.update-ad-btn {
    margin-bottom: 1rem;
}

/* 加载状态 */
.loading-state {
    text-align: center;
    padding: 2rem;
}

/* 错误状态 */
.error-state {
    text-align: center;
    padding: 2rem;
}

/* 商品卡片 */
.product-card {
    margin-bottom: 2rem;
}

.product-image-wrapper {
    width: 100%;
    height: 200px;
    border-radius: 6px;
    overflow: hidden;
}

.product-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-info {
    margin-top: 1rem;
}

.product-info h3 {
    font-size: 1.5rem;
    margin-bottom: 0.5rem;
}

.product-info p {
    margin: 0.5rem 0;
    font-size: 1rem;
}

.product-info p strong {
    color: #666;
}

/* 响应式设计 */
@media (max-width: 480px) {
    .product-image-wrapper {
        height: 150px;
    }

    .product-info {
        margin-top: 1rem;
    }
}
</style>